/**
 * Created by Joe on 2017/7/5 0005.
 */
var Basis = {
    create: {
        form: "#goodsext-form",
        modal: "#basis-new-modal",
        datatable: '#DataTables_params',
        query_form: "#query-form",
        validator: ""
    },
    detail: {
        form: "#detail-form",
        modal: "#basis-params-modal",
        validator: ""
    },
    create_em: {
        form: "#ext-machine-form",
        modal: "#basis-newmachine-modal",
        datatable: '#DataTables_params_machine',
        query_form: "#query-machine-form",
        validator: ""
    },
    detail_em: {
        form: "#em-detail-form",
        modal: "#basis-machine-modal"
    },
    fields: {
        selects: [], //下拉框
        radios: [],//单选框
        checkboxs: [],//复选款
        textareas: [],//多行文本框
        selfDefine: [{"field": "metroLine ", "selector": "a.metro_line"}]
    }
};
$(document).ready(function () {
    initTables();
    initFormValidate();
    /*初始化百度上传*/
    Uploader.initUploader(Uploader.server.import);
    /*上传按钮代理事件触发*/
    $('#import-data-form').on('click', '.uploader', function (e) {
        $('#filePicker input[name=file]').click();
        Uploader.target_alert = "import-data-form";
    });
    /************************to add new ************************/
    $('#btn-create').on('click', function () {
        Utils.clearForm(Basis.create.form);
        $(Basis.create.modal).modal("toggle");
    });
    $('#btn-create-extmachine').on('click', function () {
        Utils.clearForm(Basis.create_em.form);
        $(Basis.create_em.modal).modal("toggle");
    });
    $('#btn-import').on('click', function () {
        $("#basis-import-modal").modal("toggle");
    });
    /************************detail and remove  ************************/
    $('.btn-detail-address').on('click', function () {
        $("#basis-address-modal").modal("toggle");
    });
    /** goods ext create ,update,  detail and delete */
    $(Basis.create.datatable).on('click', ".btn-detail", function () {
        requestDetail($(this).siblings("input").val());
    });
    $(Basis.create.datatable).on('click', ".btn-delete", function () {
        var $tr = $(this).parents('tr');
        var row = $(Basis.create.datatable).DataTable().row($tr);
        row.remove().draw();
        var url = /*[[@{/removeGoodExt}]]*/ 'removeGoodExt';
        Utils.ajaxSubmit(url + "/" + $(this).siblings("input").val(), {}, function (data) {
            if (data.result == "success") {
                layer.msg('备件删除成功');
            }
            if (data.result == "fail") {
                Utils.errorAlert("备件删除成功")
            }
        });
    });
    $('#saveNewGoodsExt').on('click', function () {
        if ($(Basis.create.form).valid()) {
            requestCreate();
        } else {
            Basis.create.validator.focusInvalid();
        }
    });
    $('#updateGoodsExt').on('click', function () {
        if ($(Basis.detail.form).valid()) {
            requestUpdate();
        } else {
            Basis.detail.validator.focusInvalid();
        }
    });
    $('#cancelBtn').on('click', function () {
        $(Basis.create.modal).modal("toggle");
    });
    /** goods ext machine create ,update, detail and delete */
    $(Basis.create_em.datatable).on('click', ".btn-detail", function () {
        requestMachineDetail($(this).siblings("input").val());
    });
    $(Basis.create_em.datatable).on('click', ".btn-delete", function () {
        var $tr = $(this).parents('tr');
        var row = $(Basis.create_em.datatable).DataTable().row($tr);
        row.remove().draw();
        var url = /*[[@{/removeGoodExtMachine}]]*/ 'removeGoodExtMachine';
        Utils.ajaxSubmit(url + "/" + $(this).siblings("input").val(), {}, function (data) {
            if (data.result == "success") {
                layer.msg('备件删除成功');
            }
            if (data.result == "fail") {
                Utils.errorAlert(data.result.errorMessage);
            }
        });
    });
    $('#saveNewExtMachine').on('click', function () {
        if ($(Basis.create_em.form).valid()) {
            requestCreateMachine();
        } else {
            Basis.create_em.validator.focusInvalid();
        }
    });
    $('#btn-cancel-em').on('click', function () {
        $(Basis.create_em.modal).modal("toggle");
    });
    $('#query-ext').on('click', function () {
        var machine = $("#query-form").find("input[name='machine']").val();
        var part = $("#query-form").find("input[name='part']").val();
        clearAlerts("query-form");
        if ($.trim(machine) == '' && $.trim(part) == '') {
            alerts("query-form", 2, "请输入查询条件");
            return;
        }
        $(Basis.create.datatable).DataTable().rows().remove().draw();
        var url = /*[[@{/queryGoodsBasis}]]*/ 'queryGoodsBasis';
        var param = $(Basis.create.query_form).serialize();
        Utils.ajaxSubmit(url, param, function (data) {
            if (data.result == "success") {
                addTableRow(data.content, Basis.create.datatable);
            }
        });
    });
    $('#query-ext-machine').on('click', function () {
        var machine = $("#query-machine-form").find("input[name='machine']").val();
        clearAlerts("query-machine-form");
        if ($.trim(machine) == '') {
            alerts("query-machine-form", 2, "请输入查询条件");
            return;
        }
        $(Basis.create_em.datatable).DataTable().rows().remove().draw();
        var url = /*[[@{/queryExtMachine}]]*/ 'queryExtMachine';
        var param = $(Basis.create_em.query_form).serialize();
        Utils.ajaxSubmit(url, param, function (data) {
            if (data.result == "success") {
                addMachineTableRow(data.content, Basis.create_em.datatable);
            }
        });
    });
});

function requestCreate() {
    var url = /*[[@{/saveNewGoodsExt}]]*/ 'saveNewGoodsExt';
    var param = $(Basis.create.form).serialize();
    Utils.ajaxSubmit(url, param, function (data) {
        console.log("data: ", data);
        if (data.result == "success") {
            $(Basis.create.modal).modal("toggle");
            addTableRow(data.content, Basis.create.datatable);
        }
        if (data.result == "fail") {
            Utils.errorAlert(data.errorMessage);
        }
    });
}
function requestUpdate() {
    var url = /*[[@{/updateGoodsExt}]]*/ 'updateGoodsExt';
    var param = $(Basis.detail.form).serialize();
    Utils.ajaxSubmit(url, param, function (data) {
        console.log("data: ", data);
        if (data.result == "success") {
            $(Basis.detail.modal).modal("toggle");
        }
        if (data.result == "fail") {
            Utils.errorAlert(data.errorMessage);
        }
    });
}
function requestCreateMachine() {
    var url = /*[[@{/saveGoodsExtMachine}]]*/ 'saveGoodsExtMachine';
    var param = $(Basis.create_em.form).serialize();
    Utils.ajaxSubmit(url, param, function (data) {
        console.log("data: ", data);
        if (data.result == "success") {
            $(Basis.create_em.modal).modal("toggle");
            addMachineTableRow(data.content, Basis.create_em.datatable);
        }
        if (data.result == "fail") {
            Utils.errorAlert(data.errorMessage);
        }
    });
}
function requestDetail(id) {
    var url = /*[[@{/getGoodsExt}]]*/ 'getGoodsExt';
    Utils.clearForm(Basis.detail.form);
    $("#real_img").empty();
    Utils.ajaxSubmit(url + "/" + id, {}, function (data) {
        console.log("data ： ", data);
        if (data.result == "success") {
            Utils.fillForms(data.content, Basis.fields);
            $(Basis.detail.modal).modal("toggle");
        }
        if (data.result == "fail") {
            Utils.errorAlert(data.errorMessage);
        }
    });
}
function requestMachineDetail(id) {
    var url = /*[[@{/getExtMachineBy}]]*/ 'getExtMachineBy';
    Utils.clearForm(Basis.detail_em.form);
    Utils.ajaxSubmit(url + "/" + id, {}, function (data) {
        console.log("data ： ", data);
        if (data.result == "success") {
            Utils.fillForms(data.content, Basis.fields);
            $(Basis.detail_em.modal).modal("toggle");
        }
        if (data.result == "fail") {
            Utils.errorAlert(data.errorMessage);
        }
    });
}
/**添加table行*/
function addTableRow(goodsList, targetEle) {
    $.each(goodsList, function (k, v) {
        var btnRemoveEle = '<input type="hidden" value="' + v.id + '"> <a class="btn btn-primary btn-detail" >查看明细</a>';
        btnRemoveEle = btnRemoveEle.concat('&nbsp;&nbsp;&nbsp;<a class="btn btn-danger btn-delete">删除</a>');
        $(targetEle).dataTable().fnAddData([v.machineCategory, v.productGroup, v.productSeries, v.universalModel, v.machine, v.part, v.substitutePart, btnRemoveEle]);
    });
}
/**添加table行*/
function addMachineTableRow(goodsList, targetEle) {
    $.each(goodsList, function (k, v) {
        var btnRemoveEle = '<input type="hidden" value="' + v.id + '"> <a class="btn btn-primary btn-detail" >查看明细</a>';
        btnRemoveEle = btnRemoveEle.concat('&nbsp;&nbsp;&nbsp;<a class="btn btn-danger btn-delete">删除</a>');
        $(targetEle).dataTable().fnAddData([v.machineCategory, v.productGroup, v.productSeries, v.universalModel, v.machine, v.model, btnRemoveEle]);
    });
}
function initTables() {
    var table = $('#DataTables_address').DataTable({
        "paging": true,
        "searching": true,
        "info": true,
        "ordering": true,
        "language": {
            "url": "../vendor/datatables/zh-cn.json"
        }
    });
    $('#DataTables_address tbody').on('click', 'tr', function () {
        var data = table.row(this).data();
    });
    var extTable = $(Basis.create.datatable).DataTable({
        "paging": true,
        "searching": true,
        "info": true,
        "ordering": true,
        "language": {
            "url": "../vendor/datatables/zh-cn.json"
        }
    });
    $('#DataTables_params tbody').on('click', 'tr', function () {
        var data = extTable.row(this).data();
    });
    var extMachineTable = $(Basis.create_em.datatable).DataTable({
        "paging": true,
        "searching": true,
        "info": true,
        "ordering": true,
        "language": {
            "url": "../vendor/datatables/zh-cn.json"
        }
    });
    $('#DataTables_params_machine tbody').on('click', 'tr', function () {
        var data = extMachineTable.row(this).data();
    });
}

function initFormValidate() {
    Basis.create.validator = $(Basis.create.form).validate({
        errorElement: "span",
        errorClass: "error-block",
        focusInvalid: true,
        rules: {
            machine: {required: true, maxlength: 15},
            model: {required: false, maxlength: 15},
            part: {required: true, maxlength: 15},
            partDesc: {required: false, maxlength: 15},
            orbitsAspect: {required: false, maxlength: 50},
            cru: {required: false, maxlength: 15},
            rid: {required: false, maxlength: 10},
            rohs: {required: false, maxlength: 15},
            rG: {required: false, maxlength: 15},
            ump: {required: false, maxlength: 15},
            substitutePart: {required: false, maxlength: 15},
            consumable: {required: false, maxlength: 15}
        },
        messages: {
            machine: {required: "machine必须输入", maxlength: $.validator.format("长度不能超过{0}")},
            model: {maxlength: $.validator.format("长度不能超过{0}")},
            part: {required: "PN必须输入", maxlength: $.validator.format("长度不能超过{0}")},
            partDesc: {maxlength: $.validator.format("长度不能超过{0}")},
            orbitsAspect: {maxlength: $.validator.format("长度不能超过{0}")},
            cru: {maxlength: $.validator.format("长度不能超过{0}")},
            rid: {maxlength: $.validator.format("长度不能超过{0}")},
            rohs: {maxlength: $.validator.format("长度不能超过{0}")},
            rG: {maxlength: $.validator.format("长度不能超过{0}")},
            ump: {maxlength: $.validator.format("长度不能超过{0}")},
            substitutePart: {maxlength: $.validator.format("长度不能超过{0}")},
            consumable: {maxlength: $.validator.format("长度不能超过{0}")}
        }
    });
    Basis.detail.validator = $(Basis.detail.form).validate({
        errorElement: "span",
        errorClass: "error-block",
        focusInvalid: true,
        rules: {
            machine: {required: true, maxlength: 15},
            model: {required: false, maxlength: 15},
            part: {required: true, maxlength: 15},
            partDesc: {required: false, maxlength: 15},
            orbitsAspect: {required: false, maxlength: 50},
            cru: {required: false, maxlength: 15},
            rid: {required: false, maxlength: 15},
            rohs: {required: false, maxlength: 15},
            rG: {required: false, maxlength: 15},
            ump: {required: false, maxlength: 15},
            substitutePart: {required: false, maxlength: 15},
            consumable: {required: false, maxlength: 15}
        },
        messages: {
            machine: {required: "machine必须输入", maxlength: $.validator.format("长度不能超过{0}")},
            model: {maxlength: $.validator.format("长度不能超过{0}")},
            part: {required: "PN必须输入", maxlength: $.validator.format("长度不能超过{0}")},
            partDesc: {maxlength: $.validator.format("长度不能超过{0}")},
            orbitsAspect: {maxlength: $.validator.format("长度不能超过{0}")},
            cru: {maxlength: $.validator.format("长度不能超过{0}")},
            rid: {maxlength: $.validator.format("长度不能超过{0}")},
            rohs: {maxlength: $.validator.format("长度不能超过{0}")},
            rG: {maxlength: $.validator.format("长度不能超过{0}")},
            ump: {maxlength: $.validator.format("长度不能超过{0}")},
            substitutePart: {maxlength: $.validator.format("长度不能超过{0}")},
            consumable: {maxlength: $.validator.format("长度不能超过{0}")}
        }
    });

    Basis.create_em.validator = $(Basis.create_em.form).validate({
        errorElement: "span",
        errorClass: "error-block",
        focusInvalid: true,
        rules: {
            machine: {required: true, maxlength: 15},
            machineCategory: {required: false, maxlength: 15},
            productGroup: {required: true, maxlength: 15},
            productSeries: {required: false, maxlength: 15},
            universalModel: {required: false, maxlength: 15}
        },
        messages: {
            machine: {required: "machine必须输入", maxlength: $.validator.format("长度不能超过{0}")},
            machineCategory: {maxlength: $.validator.format("长度不能超过{0}")},
            productGroup: {required: "PN必须输入", maxlength: $.validator.format("长度不能超过{0}")},
            productSeries: {maxlength: $.validator.format("长度不能超过{0}")},
            universalModel: {maxlength: $.validator.format("长度不能超过{0}")}
        }
    });
}